package com.beiing.tianshuai.tianshuai.interest;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.InterestVideoDetailReplyAdapter;
import com.beiing.tianshuai.tianshuai.app.AppConstant;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.entity.CodeBean;
import com.beiing.tianshuai.tianshuai.entity.FollowResultBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.fragment.EmotionCompleteFragment;
import com.beiing.tianshuai.tianshuai.interest.entity.InterestVideoDetailBean;
import com.beiing.tianshuai.tianshuai.interest.presenter.InterestVideoDetailPresenter;
import com.beiing.tianshuai.tianshuai.interest.view.InterestVideoDetailViewImpl;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.mine.ui.NewPersonalIndexActivity;
import com.beiing.tianshuai.tianshuai.rx.MsgEvent;
import com.beiing.tianshuai.tianshuai.rx.RxBus;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.DisplayUtil;
import com.beiing.tianshuai.tianshuai.util.GlobalOnItemClickManagerUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.NetBitmapUtils;
import com.beiing.tianshuai.tianshuai.util.ScreenUtils;
import com.beiing.tianshuai.tianshuai.widget.CircleImageView;
import com.beiing.tianshuai.tianshuai.widget.CustomProgressDialog;
import com.beiing.tianshuai.tianshuai.widget.MyRefreshHeader;
import com.beiing.tianshuai.tianshuai.widget.RoundAngleImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.mic.etoast2.Toast;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.open.utils.ThreadManager;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.tianshuai.easypopup.EasyPopup;
import com.tianshuai.easypopup.HorizontalGravity;
import com.tianshuai.easypopup.VerticalGravity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;
import cn.magicwindow.mlink.annotation.MLinkRouter;
import me.shihao.library.XStatusBarHelper;

import static com.beiing.tianshuai.tianshuai.app.HttpRequestConstant.USER_PIC_HEAD;
import static com.beiing.tianshuai.tianshuai.app.HttpRequestConstant.VIDEO_PIC_HEAD;

@MLinkRouter(keys={"tinsine_video"})
public class InterestVideoDetailActivity extends AppCompatActivity implements InterestVideoDetailViewImpl {

//    /**
//     * 视频播放容器
//     */
//    @BindView(R.id.status_bar_background)
//    View mStatusBarBackground;

    /**
     * 视频播放容器
     */
    @BindView(R.id.rl_video_container)
    RelativeLayout mHeaderContentView;

    /**
     * 视频播放容器
     */
    @BindView(R.id.btn_back)
    ImageButton mBtnBack;

    /**
     * 视频标题
     */
    @BindView(R.id.tv_video_title)
    TextView mTvVideoTitle;

    /**
     * 作者头像
     */
    @BindView(R.id.civ_user_avatar)
    CircleImageView mUserAvatar;

    /**
     * 作者头像
     */
    @BindView(R.id.tv_user_university)
    TextView mUserUniversity;

    /**
     * 作者昵称
     */
    @BindView(R.id.tv_user_name)
    TextView mUserNickname;

    /**
     * 推荐视频父布局
     */
    @BindView(R.id.ll_recommend_video_container)
    LinearLayout mLlRecommendVideoContainer;

    /**
     * 视频的评论列表
     */
    @BindView(R.id.rv_reply)
    RecyclerView mRvReply;

    /**
     * 刷新布局
     */
    @BindView(R.id.srl_my_refresh_layout)
    SmartRefreshLayout mSrlMyRefreshLayout;

    /**
     * 刷新头布局
     */
    @BindView(R.id.interest_header)
    MyRefreshHeader mInterestHeader;

    /**
     * 刷新Footer布局
     */
    @BindView(R.id.interest_footer)
    ClassicsFooter mInterestFooter;

    /**
     * 评论输入框
     */
    @BindView(R.id.et_video_reply)
    EditText mEtVideoReply;

    /**
     * 发送评论
     */
    @BindView(R.id.btn_submit_reply)
    TextView mBtnSubmitReply;

    /**
     * 分享按钮
     */
    @BindView(R.id.btn_share_video)
    ImageButton mBtnShareVideo;

    /**
     * 视频点赞
     */
    @BindView(R.id.tv_video_up)
    TextView mTvVideoUp;

    /**
     * 是否关注作者
     */
    @BindView(R.id.tv_is_followed)
    TextView mTvIsFollowed;

    /**
     * 加载动画的背景
     */
    @BindView(R.id.loading_background)
    View mLoadingBackground;

    /**
     * 评论内容为空的提示
     */
    @BindView(R.id.txt_empty_warning)
    TextView mCommentEmptyWarning;

    /**
     * 排序
     */
    @BindView(R.id.btn_order_by)
    ImageButton mBtnOrderBy;

    /**
     * 排序
     */
    @BindView(R.id.ll_web_view_container)
    LinearLayout mLlWebViewContainer;

//    /**
//     * 收藏按钮
//     */
//    @BindView(R.id.btn_collect)
//    Button mBtnCollect;

    @BindView(R.id.iv_face)
    ImageView ivFace;
    @BindView(R.id.iv_keyboard)
    ImageView ivKeyBoard;
    @BindView(R.id.fl_emotionview_main)
    FrameLayout mEmotionLayout;
    @BindView(R.id.scroll_view)
    ScrollView mScrollView;



    /**
     * 视频播放容器
     */
    private WebView mWvVideoContainer;

    /**
     * 页容量
     */
    public static final int PAGE_SIZE = 4;

    /**
     * 分享地址头部
     */
    private static final String URL = "http://www.tianshuai.com.cn/index.php/Home/video/video_web/id/";

    /**
     * 视频id
     */
    private String mVid;

    /**
     * presenter
     */
    private InterestVideoDetailPresenter mPresenter;

    /**
     * 评论列表适配器
     */
    private InterestVideoDetailReplyAdapter mAdapter;

    /**
     * 是否加载完成
     */
    private boolean isLoadFinished;

    /**
     * 是否为刷新操作
     */
    private boolean isRefresh;

    /**
     * 当前分页的页码
     */
    private int pageNum = 1;

    /**
     * 作者的uid
     */
    private String mToUid;

    /**
     * 用户是否点赞
     */
    private boolean isThing;

    /**
     * 当前点赞的数量
     */
    private String mThingNum;

    /**
     * 视频分享dialog
     */
    private Dialog bottomDialog;

    /**
     * 第三方分享
     */
    private Tencent mTencent;

    /**
     * 分享缩略图
     */
    private Bitmap thumb;

    /**
     * 视频资料
     * 在网络请求回调前为空
     */
    private InterestVideoDetailBean.DataBean.VideoInfoBean mVideoInfoBean;

    /**
     * 详情数据重新请求次数
     */
    private int retryRequestDetailCount = 0;

    /**
     * 加载动画的渐变动画
     */
    private AlphaAnimation mHideAnimation;

    /**
     * 判断用户是否离开当前界面
     */
    private boolean isOnPause;

    /**
     * 上下文关系
     */
    private Context mContext;

    /**
     * 是否为回复评论
     */
    private boolean isReplyComment = false;

    /**
     * 当前正在回复的rid（回复id）
     */
    private String mRepliedRId;

    /**
     * 当前正在回复的cid（评论id）
     */
    private String mRepliedCId;

    /**
     * 当前回复的源内容
     */
    private String mRepliedContent;

    /**
     * 回复的item的tableType 0-回复评论 2-回复评论的回复
     */
    private String mRepliedTableType;

    /**
     * 回复目标的用户id
     */
    private String mRepliedToUid;

    /**
     * 更多菜单弹窗
     */
    private EasyPopup mPopup;

    /**
     * 请求评论的排序方式
     * 0 - 时间降序
     * 1 - 时间升序
     * 2 - 点赞数量
     */
    private int mCode = 0;

    private EmotionCompleteFragment emotionCompleteFragment;
    private boolean emotionLayoutShow;      //表情面板是否显示
    private GlobalOnItemClickManagerUtils globalOnItemClickManager;
    private InputMethodManager imm;

    /**
     * 分享监听事件
     */
    private IUiListener mIUiListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            Toast.makeText(mContext, "分享成功", 0).show();
        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(mContext, "分享失败", 0).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(mContext, "取消分享", 0).show();
        }
    };


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_interest_video_detail);
        mContext = this;
        ButterKnife.bind(this);
        mPopup = new EasyPopup(mContext)
                .setContentView(R.layout.menu_video_reply_order_by)
                .setAnimationStyle(R.style.QQPopAnim)
                .setFocusAndOutsideEnable(true)
                .createPopup();
        addWebView();
        CustomProgressDialog.showLoading(mContext, "", true);
        CustomProgressDialog.setCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });

        XStatusBarHelper.tintStatusBar(this, 0xFF000000);

        Intent intent = getIntent();
        mTencent = Tencent.createInstance("1106377834", mContext);
        mVid = intent.getStringExtra("vid");

        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        initRefreshLayout();
        initRecyclerView();
        initVideoHeight();
        initPresenter();
        initListener();
        initEmotionMainFragment();
    }

    private void initEmotionMainFragment() {
        globalOnItemClickManager = GlobalOnItemClickManagerUtils.getInstance(mContext);
        globalOnItemClickManager.attachToEditText(mEtVideoReply);
        emotionCompleteFragment = new EmotionCompleteFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.fl_emotionview_main, emotionCompleteFragment);
        transaction.commit();
    }

    private void addWebView() {
        WindowManager manager = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        int width = outMetrics.widthPixels;
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width, width / 16 * 9);
        mLlWebViewContainer.setLayoutParams(layoutParams);
        mWvVideoContainer = new WebView(mContext);
        mWvVideoContainer.setHorizontalScrollBarEnabled(false);
        mWvVideoContainer.setVerticalScrollBarEnabled(false);
        mWvVideoContainer.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        mLlWebViewContainer.addView(mWvVideoContainer, new RelativeLayout.LayoutParams(WebView.LayoutParams.MATCH_PARENT, WebView.LayoutParams.MATCH_PARENT));
    }

    //根据屏幕高宽比设置video父容器高度
    private void initVideoHeight() {
        ViewGroup.LayoutParams layoutParams = mHeaderContentView.getLayoutParams();
        if ((float) ScreenUtils.getScreenHeight(mContext) / (float) ScreenUtils.getScreenWidth(mContext) <= 1.78) {
            layoutParams.height = DisplayUtil.dip2px(mContext, 205);
            if ((float) ScreenUtils.getScreenHeight(mContext) / (float) ScreenUtils.getScreenWidth(mContext) <= 1.78) {
                layoutParams.height = DisplayUtil.dip2px(mContext, 204);
                mHeaderContentView.setLayoutParams(layoutParams);
            } else {
                layoutParams.height = DisplayUtil.dip2px(mContext, 234);
                mHeaderContentView.setLayoutParams(layoutParams);
            }
        }
    }

    /**
     * 初始化refresh layout
     * 设置下拉和上拉动作的listener
     */
    private void initRefreshLayout() {
        mSrlMyRefreshLayout.setRefreshHeader(new MyRefreshHeader(mContext));
        mSrlMyRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        // =================== 下拉刷新 =====================
        mSrlMyRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                isRefresh = true;
                isLoadFinished = false;
                mSrlMyRefreshLayout.setLoadmoreFinished(false);
                mPresenter.getVideoDetail(mVid, "", String.valueOf(PAGE_SIZE), pageNum, UserInfoBean.getUid(mContext), mCode);
            }
        });
        // =================== 上拉加载 =====================
        mSrlMyRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {

            private String mLastRid = "";
            private String mLastCid = "";

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (!isLoadFinished) {
                    pageNum++;
                    List<InterestVideoDetailBean.DataBean.VideoCommentBean> list = mAdapter.getList();
                    for (int i = list.size() - 1; i >= 0; i--) {
                        InterestVideoDetailBean.DataBean.VideoCommentBean bean = list.get(i);
                        if ("0".equals(bean.getTableType())) {
                            mLastCid = bean.getId();
                            break;
                        }
                    }
                    for (int i = list.size() - 1; i >= 0; i--) {
                        InterestVideoDetailBean.DataBean.VideoCommentBean bean = list.get(i);
                        if ("2".equals(bean.getTableType())) {
                            mLastRid = bean.getId();
                            break;
                        }
                    }
                    mPresenter.getMoreReply(mVid, mLastCid, String.valueOf(PAGE_SIZE), pageNum, UserInfoBean.getUid(mContext), mLastRid, mCode);
                } else {
                    mSrlMyRefreshLayout.setLoadmoreFinished(true);
                    mSrlMyRefreshLayout.finishLoadmore(true);
                }
            }
        });
    }

    private void initRecyclerView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRvReply.setNestedScrollingEnabled(false);
        mRvReply.setLayoutManager(linearLayoutManager);
        mAdapter = new InterestVideoDetailReplyAdapter(mContext);
        mRvReply.setAdapter(mAdapter);
    }

    private void initPresenter() {
        mPresenter = new InterestVideoDetailPresenter(this);
        mPresenter.getVideoDetail(mVid, "", String.valueOf(PAGE_SIZE), pageNum, UserInfoBean.getUid(mContext), mCode);
    }

    /**
     * 初始化点击监听
     */
    private void initListener() {
        // 排序
        mBtnOrderBy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initPopupWindow();
                int i = v.getLayoutParams().width / 2 + DensityUtils.dp2px(mContext, 6);
                mPopup.showAtAnchorView(v, VerticalGravity.BELOW, HorizontalGravity.ALIGN_RIGHT, i, -DensityUtils.dp2px(mContext, 15));
            }
        });

        // 回复的昵称点击事件
        mAdapter.setOnUsernameReplyToClickListener(new InterestVideoDetailReplyAdapter.OnUsernameReplyToClickListener() {
            @Override
            public void onUsernameReplyToClick(View v, InterestVideoDetailBean.DataBean.VideoCommentBean bean) {
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                intent.putExtra("uid", bean.getToUid());
                startActivity(intent);
            }
        });

        // 头像点击事件
        mAdapter.setAvatarClickListener(new InterestVideoDetailReplyAdapter.OnAvatarClickListener() {
            @Override
            public void onAvatarClick(InterestVideoDetailBean.DataBean.VideoCommentBean bean, int position) {
                if (TextUtils.equals(bean.getTableType(), "0")) {
                    Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                    intent.putExtra("uid", bean.getUid());
                    startActivity(intent);
                } else if (TextUtils.equals(bean.getTableType(), "2")) {
                    Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                    intent.putExtra("uid", bean.getFormUid());
                    startActivity(intent);
                }
            }
        });

        // 条目内容点击事件，弹出回复和删除的dialog
        mAdapter.setItemClickListener(new InterestVideoDetailReplyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(TextView v, final InterestVideoDetailBean.DataBean.VideoCommentBean bean, final int position) {
                if (TextUtils.equals(UserInfoBean.getUid(mContext), bean.getUid()) || TextUtils.equals(UserInfoBean.getUid(mContext), bean.getFormUid())) {
                    PopupMenu popupMenu = new PopupMenu(mContext, v);
                    popupMenu.inflate(R.menu.menu_interest_reply);
                    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem item) {
                            int itemId = item.getItemId();
                            switch (itemId) {
                                case R.id.item_delete:
                                    switch (bean.getTableType()) {
                                        case "0":
                                            mPresenter.deleteReply(bean.getId(), bean.getUid(), position, "1");
                                            break;
                                        case "2":
                                            mPresenter.deleteReply(bean.getId(), bean.getFormUid(), position, "2");
                                            break;
                                    }
                                    break;
                            }
                            return false;
                        }
                    });
                    popupMenu.show();
                } else {
                    PopupMenu popupMenu = new PopupMenu(mContext, v);
                    popupMenu.inflate(R.menu.menu_interest_reply_others);
                    popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        @Override
                        public boolean onMenuItemClick(MenuItem item) {
                            int itemId = item.getItemId();
                            switch (itemId) {
                                case R.id.item_reply:
                                    String uid = UserInfoBean.getUid(mContext);
                                    if (TextUtils.isEmpty(uid)) {
                                        Intent intent = new Intent(mContext, LoginActivity.class);
                                        startActivity(intent);
                                        return false;
                                    }
                                    if (emotionLayoutShow){
                                        mEmotionLayout.setVisibility(View.GONE);
                                        emotionLayoutShow = false;
                                    }
                                    mEtVideoReply.requestFocus();
                                    mEtVideoReply.setHint("回复 " + bean.getName());
                                    // 由于setHint需要重新绘制editText 所以这里需要延时执行弹出输入框
                                    mEtVideoReply.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (imm != null) {
                                                imm.showSoftInput(mEtVideoReply, 0);
                                            }
                                        }
                                    }, 250);
                                    isReplyComment = true;
                                    mRepliedContent = bean.getContent();
                                    mRepliedTableType = bean.getTableType();
                                    if ("0".equals(mRepliedTableType)) {
                                        mRepliedCId = bean.getId();
                                        mRepliedRId = "-1";
                                        mRepliedToUid = bean.getUid();
                                    } else if ("2".equals(mRepliedTableType)) {
                                        mRepliedCId = bean.getCid();
                                        mRepliedRId = bean.getId();
                                        mRepliedToUid = bean.getFormUid();
                                    }
//                                    mPresenter.addCommentReply(bean.getVid(), bean.getId(), UserInfoBean.getUid(mContext), bean.getUid(), "测试测试", bean.getContent());
                                    break;
                            }
                            return false;
                        }
                    });
                    popupMenu.show();
                }
            }
        });

        // 过渡动画监听
        CustomProgressDialog.setListener(new CustomProgressDialog.OnDismiss() {
            @Override
            public void onDismissListener() {
                setHideAnimation(mLoadingBackground);
            }
        });

        // 设置评论的点赞监听事件
        mAdapter.setListener(new InterestVideoDetailReplyAdapter.OnUpClickListener() {

            @Override
            public void onUpClickListener(View v, InterestVideoDetailBean.DataBean.VideoCommentBean bean) {
                String uid = UserInfoBean.getUid(mContext);
                if (TextUtils.isEmpty(uid)) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                String toUid = bean.getToUid();
                String cId = bean.getId();
                String vid = bean.getVid();
                if (TextUtils.equals(bean.getTableType(), "0")) {
                    mPresenter.setPraiseReply(cId, vid, uid, toUid);
                    int thingNum = Integer.valueOf(bean.getThing());
                    boolean isThing = bean.getVideoCommentThing() == 1;
                    Drawable isThingDrawable = mContext.getResources().getDrawable(
                            isThing ? R.drawable.ic_comment_up : R.drawable.ic_video_up_checked
                    );
                    isThingDrawable.setBounds(
                            0,
                            0,
                            isThingDrawable.getMinimumWidth(),
                            isThingDrawable.getMinimumHeight()
                    );
                    ((TextView) v).setCompoundDrawables(
                            null,
                            null,
                            isThingDrawable,
                            null);
                    if (isThing) {
                        thingNum--;
                        bean.setVideoCommentThing(0);
                    } else {
                        thingNum++;
                        bean.setVideoCommentThing(1);
                    }
                    bean.setThing(String.valueOf(thingNum));
                    ((TextView) v).setText(bean.getThing());
                } else if (TextUtils.equals(bean.getTableType(), "2")) {
                    mPresenter.setPraiseCommentReply(bean.getCid(), vid, uid, toUid, bean.getId());
                    int thingNum = Integer.valueOf(bean.getThing());
                    boolean isThing = bean.getVideoReplyThing() == 1;
                    Drawable isThingDrawable = mContext.getResources().getDrawable(
                            isThing ? R.drawable.ic_comment_up : R.drawable.ic_video_up_checked
                    );
                    isThingDrawable.setBounds(
                            0,
                            0,
                            isThingDrawable.getMinimumWidth(),
                            isThingDrawable.getMinimumHeight()
                    );
                    ((TextView) v).setCompoundDrawables(
                            null,
                            null,
                            isThingDrawable,
                            null);
                    if (isThing) {
                        thingNum--;
                        bean.setVideoReplyThing(0);
                    } else {
                        thingNum++;
                        bean.setVideoReplyThing(1);
                    }
                    bean.setThing(String.valueOf(thingNum));
                    ((TextView) v).setText(bean.getThing());
                }

            }
        });

        // 分享视频
        mBtnShareVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mVideoInfoBean == null) {
                    return;
                }
                showShareDialog();
            }
        });

        // 关注作者
        mTvIsFollowed.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (!TextUtils.isEmpty(mToUid)) {
                    String uid = UserInfoBean.getUid(mContext);
                    if (TextUtils.isEmpty(uid)) {
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    mPresenter.setFollowed(uid, mToUid);
                }
            }
        });

        // 返回操作
        mBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 点赞操作
        mTvVideoUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String uid = UserInfoBean.getUid(mContext);
                if (TextUtils.isEmpty(uid)) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                mPresenter.getPraiseResult(mVid, uid, "1");
                isThing = !isThing;
                RxBus.getInstanceBus().post(new MsgEvent<>("视频详情点赞", isThing, Integer.valueOf(mVid)));
                mThingNum = String.valueOf(isThing ? Integer.valueOf(mThingNum) - 1 : Integer.valueOf(mThingNum) + 1);
                Drawable drawable = getResources().getDrawable(isThing ? R.drawable.ic_comment_up : R.drawable.ic_video_up_checked);
                drawable.setBounds(
                        0, 0,
                        drawable.getMinimumWidth(),
                        drawable.getMinimumHeight()
                );
                mTvVideoUp.setCompoundDrawables(
                        drawable,
                        null,
                        null,
                        null);
                mTvVideoUp.setText(mThingNum);
            }
        });

        // 评论输入框的焦点监听 用来做用户点击输入框时右侧按钮的变化
        mEtVideoReply.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mBtnShareVideo.setVisibility(View.GONE);
//                    mBtnCollect.setVisibility(View.GONE);
                    mBtnSubmitReply.setVisibility(View.VISIBLE);
                    mEmotionLayout.setVisibility(View.GONE);
                    ivFace.setVisibility(View.VISIBLE);
                    ivKeyBoard.setVisibility(View.GONE);
                } else {
                    mBtnShareVideo.setVisibility(View.VISIBLE);
//                    mBtnCollect.setVisibility(View.VISIBLE);
                    mBtnSubmitReply.setVisibility(View.GONE);
                }
            }
        });

        mEtVideoReply.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    String uid = UserInfoBean.getUid(mContext);
                    if (TextUtils.isEmpty(uid)) {
                        Intent intent = new Intent(mContext, LoginActivity.class);
                        startActivity(intent);
                        return false;
                    }
                    String content = mEtVideoReply.getText().toString().trim();
                    if (TextUtils.isEmpty(content)) {
                        Toast.makeText(mContext, "您还什么都没有说呢~", 0).show();
                        return false;
                    }
                    mBtnSubmitReply.setEnabled(false);
                    // 提交评论后清除输入框的焦点并隐藏软键盘
                    mEtVideoReply.clearFocus();
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(v != null ? v.getWindowToken() : null, 0);
                    }
                    mPresenter.submitReply(mVid, UserInfoBean.getUid(mContext), mToUid, content);
                }
                return false;
            }
        });

        // 修改发送按钮的样式 输入框有内容时设置发送按钮为蓝色 内容为空时为灰色
        mEtVideoReply.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mBtnSubmitReply.setBackground(ContextCompat.getDrawable(mContext,
                        TextUtils.isEmpty(s.toString().trim()) ? R.drawable.publish_gray : R.drawable.publish_blue));
            }
        });

        // 提交评论
        mBtnSubmitReply.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String uid = UserInfoBean.getUid(mContext);
                if (TextUtils.isEmpty(uid)) {
                    Intent intent = new Intent(mContext, LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                String content = mEtVideoReply.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(mContext, "您还什么都没有说呢~", 0).show();
                    return;
                }
                try {
                    content = URLEncoder.encode(content, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                mBtnSubmitReply.setEnabled(false);
                // 提交评论后清除输入框的焦点并隐藏软键盘
                mEtVideoReply.clearFocus();
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v != null ? v.getWindowToken() : null, 0);
                }
                if (!isReplyComment) {
                    mPresenter.submitReply(mVid, UserInfoBean.getUid(mContext), mToUid, content);
                } else {
                    switch (mRepliedTableType) {
                        case "0":
                            mPresenter.addCommentReply(mVid, mRepliedRId, UserInfoBean.getUid(mContext), mRepliedToUid, content, mRepliedContent, "1", mRepliedCId);
                            break;
                        case "2":
                            mPresenter.addCommentReply(mVid, mRepliedRId, UserInfoBean.getUid(mContext), mRepliedToUid, content, mRepliedContent, "2", mRepliedCId);
                            break;
                    }
                }
            }
        });

        //弹出表情输入面板
        ivFace.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivFace.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.VISIBLE);
                emotionLayoutShow = true;
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                mEmotionLayout.setVisibility(View.VISIBLE);
                mBtnSubmitReply.setVisibility(View.VISIBLE);
                mBtnShareVideo.setVisibility(View.GONE);
            }
        });

        //弹出软键盘
        ivKeyBoard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mEmotionLayout.setVisibility(View.GONE);
                ivKeyBoard.setVisibility(View.GONE);
                ivFace.setVisibility(View.VISIBLE);
                emotionLayoutShow = true;
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                mEtVideoReply.setFocusable(true);
                mEtVideoReply.setFocusableInTouchMode(true);
                mEtVideoReply.requestFocus();
            }
        });

        mScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mEmotionLayout.setVisibility(View.GONE);
                emotionLayoutShow = false;
                return false;
            }
        });
    }

    /**
     * 点击editText外部时隐藏软键盘
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev) && !isSubmitReply(ev)) {
                if (v != null) {
                    v.clearFocus();
                    if (v.getId() == R.id.et_video_reply) {
                        if (TextUtils.isEmpty(((EditText) v).getText()) && isReplyComment) {
                            isReplyComment = false;
                            ((EditText) v).setHint("添加评论");
                        }
                    }
                }
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v != null ? v.getWindowToken() : null, 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
    }

    /**
     * 初始化更多菜单
     */
    private void initPopupWindow() {
        // 按时间排序菜单
        TextView tvOrderByTime = mPopup.getView(R.id.action_order_by_time);
        // 按热度排序菜单
        TextView tvOrderByHot = mPopup.getView(R.id.action_order_by_hot);
        // 设置按时间排序点击事件
        tvOrderByTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNum = 1;
                isRefresh = true;
                isLoadFinished = false;
                mCode = mCode == 0 ? 1 : 0;
                mPresenter.getVideoDetail(mVid, "", String.valueOf(PAGE_SIZE), pageNum, UserInfoBean.getUid(mContext), mCode);
                mPopup.dismiss();
            }
        });
        // 设置按热度排序点击事件
        tvOrderByHot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageNum = 1;
                isRefresh = true;
                isLoadFinished = false;
                mCode = 2;
                mPresenter.getVideoDetail(mVid, "", String.valueOf(PAGE_SIZE), pageNum, UserInfoBean.getUid(mContext), mCode);
                mPopup.dismiss();
            }
        });

    }

    private boolean isSubmitReply(MotionEvent ev) {
        int[] submitButtonLocation = {0, 0};
        mBtnSubmitReply.getLocationInWindow(submitButtonLocation);
        int x = submitButtonLocation[0];
        int y = submitButtonLocation[1];
        int width = mBtnSubmitReply.getWidth();
        int height = mBtnSubmitReply.getHeight();
        return ev.getX() > x && ev.getX() < x + width && ev.getY() > y && ev.getY() < y + height;
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    /**
     * 弹出分享提示框
     */
    private void showShareDialog() {
        bottomDialog = new Dialog(mContext, R.style.BottomDialog);
        @SuppressLint("InflateParams") View contentView = LayoutInflater.from(mContext).inflate(R.layout.dialog_interest_detail_bottom_share, null);
        RadioButton weChatFriends = contentView.findViewById(R.id.rb_wechat_friends);
        RadioButton weChatCircle = contentView.findViewById(R.id.rb_wechat_circle);
        RadioButton qqFriends = contentView.findViewById(R.id.rb_qq_friends);
        RadioButton qqZone = contentView.findViewById(R.id.rb_qzone);

        weChatFriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToWeChatWithWebPage(mVideoInfoBean, mContext, URL + mVideoInfoBean.getId(), mVideoInfoBean.getTitle(), mVideoInfoBean.getContent(), 0);
                bottomDialog.dismiss();
            }
        });
        weChatCircle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToWeChatWithWebPage(mVideoInfoBean, mContext, URL + mVideoInfoBean.getId(), mVideoInfoBean.getTitle(), mVideoInfoBean.getContent(), 1);
                bottomDialog.dismiss();
            }
        });
        qqFriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToQQ(mVideoInfoBean.getTitle(), mVideoInfoBean.getContent(), URL + mVideoInfoBean.getId());
                bottomDialog.dismiss();
            }
        });
        qqZone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareToQZone(mVideoInfoBean.getTitle(), mVideoInfoBean.getContent(), URL + mVideoInfoBean.getId());
                bottomDialog.dismiss();
            }
        });

        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        Window window = bottomDialog.getWindow();
        if (window != null) {
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.BottomDialog_Animation);
        }
        bottomDialog.show();
        bottomDialog.setCanceledOnTouchOutside(true);
    }

    private void shareToWeChatWithWebPage(final InterestVideoDetailBean.DataBean.VideoInfoBean bean,
                                          Context context, String url, String title,
                                          String description, final int scene) {
        final IWXAPI iwxapi = WXAPIFactory.createWXAPI(context, AppConstant.WX_APP_ID);

        if (!iwxapi.isWXAppInstalled()) {
            Toast.makeText(context, "您尚未安装微信", 0).show();
            return;
        }

        WXWebpageObject wxWebpageObject = new WXWebpageObject();
        wxWebpageObject.webpageUrl = url;
        final WXMediaMessage wxMediaMessage = new WXMediaMessage(wxWebpageObject);
        wxMediaMessage.mediaObject = wxWebpageObject;
        wxMediaMessage.title = title;
        wxMediaMessage.description = description;
        new Thread(new Runnable() {
            @Override
            public void run() {
                thumb = NetBitmapUtils.getBitmap(HttpRequestConstant.VIDEO_PIC_HEAD + bean.getCover());
                thumb = Bitmap.createScaledBitmap(thumb, 200, 200, true);

                wxMediaMessage.setThumbImage(thumb);

                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = wxMediaMessage;
                req.scene = scene;

                iwxapi.sendReq(req);
            }
        }).start();
    }

    private void shareToQQ(String title, String summary, String url) {
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);         //标题
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);     //摘要
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);      //内容地址

        ThreadManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                mTencent.shareToQQ((InterestVideoDetailActivity) mContext, params, mIUiListener);
            }
        });
    }

    private void shareToQZone(String title, String summary, String url) {
        final Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);         //标题
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summary);     //摘要
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, url);      //内容地址
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, new ArrayList<String>());

        ThreadManager.getMainHandler().post(new Runnable() {
            @Override
            public void run() {
                mTencent.shareToQzone((InterestVideoDetailActivity) mContext, params, mIUiListener);
            }
        });
    }

    public void setHideAnimation(final View view) {
        if (null == view) {
            return;
        }

        if (null != mHideAnimation) {
            mHideAnimation.cancel();
        }
        // 监听动画结束的操作
        mHideAnimation = new AlphaAnimation(1.0f, 0.0f);
        mHideAnimation.setDuration(888);
        mHideAnimation.setFillAfter(true);
        mHideAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {

            }

            @Override
            public void onAnimationRepeat(Animation arg0) {

            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                view.setVisibility(View.GONE);
            }
        });
        view.startAnimation(mHideAnimation);
    }

    /**
     * 网络请求开始展示
     */
    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }
    /**
     * 回调网络请求结果
     */
    @Override
    public void onRequestSuccess (final InterestVideoDetailBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                if (mSrlMyRefreshLayout.isRefreshing()) {
                    mSrlMyRefreshLayout.finishRefresh(true);
                }
                final InterestVideoDetailBean.DataBean data = bean.getData();
                mVideoInfoBean = data.getVideoInfo().get(0);
                mToUid = mVideoInfoBean.getUid();
                RequestOptions avatarOptions = new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .centerCrop()
                        .placeholder(R.mipmap.default_avatar)
                        .override(350, 350);
                if (!isRefresh) {
                    // 加载作品
                    initWebView(mVideoInfoBean.getUrl());
                    // 设置作品标题
                    mTvVideoTitle.setText(mVideoInfoBean.getTitle());
                    // 设置作者头像
                    Glide.with(mContext.getApplicationContext())
                            .load(USER_PIC_HEAD + mVideoInfoBean.getPhoto())
                            .apply(avatarOptions)
                            .into(mUserAvatar);
                    mUserAvatar.setOnClickListener(new BGAOnNoDoubleClickListener() {
                        @Override
                        public void onNoDoubleClick(View v) {
                            Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                            intent.putExtra("uid", mVideoInfoBean.getUid());
                            startActivity(intent);
                        }
                    });
                    // 设置作者昵称
                    mUserNickname.setText(mVideoInfoBean.getName());
                    // 设置推荐视频
                    initRecommendVideos(data.getVideoShow());
                    // 设置作者学校
                    mUserUniversity.setText(mVideoInfoBean.getUnit());
                }
                // 设置点赞状态
                isThing = data.getCheckThing() == 0;
                Drawable isThingDrawable = getResources().getDrawable(isThing ?
                        R.drawable.ic_comment_up : R.drawable.ic_video_up_checked);
                isThingDrawable.setBounds(0, 0, isThingDrawable.getMinimumWidth(),
                        isThingDrawable.getMinimumHeight());
                mTvVideoUp.setCompoundDrawables(isThingDrawable,
                        null,
                        null,
                        null);
                mThingNum = mVideoInfoBean.getThingNum();
                // 设置点赞数量
                mTvVideoUp.setText(mThingNum);
                // 是否关注作者
                if (!TextUtils.equals(mToUid, UserInfoBean.getUid(mContext))) {
                    mTvIsFollowed.setVisibility(View.VISIBLE);
                    mTvIsFollowed.setText(mVideoInfoBean.getToConcern() == 0 ? "关注" : "已关注");
                }
                // 设置作品评论
                List<InterestVideoDetailBean.DataBean.VideoCommentBean> videoComment = data.getVideoComment();
                int size = videoComment.size();
                if (size == 0) {
                    isLoadFinished = true;
                    mCommentEmptyWarning.setVisibility(View.VISIBLE);
                } else if (size == PAGE_SIZE * 2) {
                    isLoadFinished = false;
                    mCommentEmptyWarning.setVisibility(View.GONE);
                    mAdapter.updateData(videoComment);
                } else {
                    isLoadFinished = true;
                    mCommentEmptyWarning.setVisibility(View.GONE);
                    mAdapter.updateData(videoComment);
                }
                break;
        }
        CustomProgressDialog.stopLoading();
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        if (retryRequestDetailCount < 5) {
            mPresenter.getVideoDetail(mVid, "", String.valueOf(PAGE_SIZE), pageNum, UserInfoBean.getUid(mContext), mCode);
            retryRequestDetailCount++;
        } else {
            retryRequestDetailCount = 0;
            Toast.makeText(this, "获取视频详情失败", 0).show();
            finish();
        }
        if (mSrlMyRefreshLayout.isRefreshing()) {
            mSrlMyRefreshLayout.finishRefresh(true);
            LogUtils.e(throwable.getMessage(), "InterestVideoDetail");
        }
    }

    /**
     * 初始化视频播放模块
     *
     * @param requestUrl 视频链接
     */
    private void initWebView(String requestUrl) {
        if (mWvVideoContainer != null) {
            WebSettings settings = mWvVideoContainer.getSettings();
            settings.setSupportZoom(true);
            settings.setJavaScriptEnabled(true);
            settings.setDomStorageEnabled(true);
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

            settings.setUseWideViewPort(true);
            settings.setLoadWithOverviewMode(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
            mWvVideoContainer.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    url = url
                            .replaceAll("&lt;", "<")
                            .replaceAll("&gt;", ">")
                            .replaceAll("&quot;", "")
                            .replaceAll("&amp;", "&");
                    Uri uri = Uri.parse(url); // url为你要链接的地址
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                    return true;
                }
            });
            LogUtils.i(requestUrl, "URL");
            requestUrl = requestUrl
                    .replaceAll("&lt;", "<")
                    .replaceAll("&gt;", ">")
                    .replaceAll("&quot;", "")
                    .replaceAll("&amp;", "&");
            mWvVideoContainer.loadUrl(requestUrl);
            mWvVideoContainer.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    if (newProgress == 100) {
                        CustomProgressDialog.stopLoading();
                    }
                    super.onProgressChanged(view, newProgress);
                }
            });
        }
    }

    /**
     * 初始化推荐视频列表
     *
     * @param videoShow 推荐视频信息
     */
    private void initRecommendVideos(final List<InterestVideoDetailBean.DataBean.VideoShowBean> videoShow) {
        // 先清除container中的所有子View 便于刷新时更新这里的内容
        mLlRecommendVideoContainer.removeAllViews();
        RequestOptions coverOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .placeholder(R.drawable.img_loading_background)
                .override(710, 400);
        RequestOptions avatarOptions = new RequestOptions()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .centerCrop()
                .placeholder(R.mipmap.default_avatar)
                .override(350, 350);
        for (int i = 0, videoShowSize = videoShow.size(); i < videoShowSize; i++) {
            final InterestVideoDetailBean.DataBean.VideoShowBean videoShowBean = videoShow.get(i);
            // 创建一个子View
            View recommendVideo = View.inflate(mContext, R.layout.item_recommend_video, null);
            // 是否显示底部分界线
            if (i == videoShowSize - 1) {
                View divider = recommendVideo.findViewById(R.id.divider);
                divider.setVisibility(View.GONE);
            }
            // 设置推荐视频封面
            RoundAngleImageView cover = recommendVideo.findViewById(R.id.riv_cover);
            Glide.with(mContext.getApplicationContext())
                    .load(VIDEO_PIC_HEAD + videoShowBean.getCover())
                    .apply(coverOptions)
                    .into(cover);
            // 设置用户头像
            CircleImageView userAvatar = recommendVideo.findViewById(R.id.civ_user_avatar);
            Glide.with(mContext.getApplicationContext())
                    .load(USER_PIC_HEAD + videoShowBean.getPhoto())
                    .apply(avatarOptions)
                    .into(userAvatar);
            // 设置用户昵称
            TextView username = recommendVideo.findViewById(R.id.tv_user_name);
            username.setText(videoShowBean.getName());
            // 用户昵称和头像的点击事件
            userAvatar.setOnClickListener(new BGAOnNoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                    intent.putExtra("uid", videoShowBean.getUid());
                    startActivity(intent);
                }
            });
            username.setOnClickListener(new BGAOnNoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                    intent.putExtra("uid", videoShowBean.getUid());
                    startActivity(intent);
                }
            });
            // 设置推荐视频标题
            TextView videoTitle = recommendVideo.findViewById(R.id.tv_title);
            videoTitle.setText(videoShowBean.getTitle());
            // 设置推荐视频浏览次数
            TextView viewCount = recommendVideo.findViewById(R.id.tv_view_count);
            viewCount.setText(MessageFormat.format("{0}次播放", videoShowBean.getView()));
            // 设置推荐视频条目的点击事件
            recommendVideo.setOnClickListener(new BGAOnNoDoubleClickListener() {
                @Override
                public void onNoDoubleClick(View v) {
                    Intent intent = new Intent(mContext, InterestVideoDetailActivity.class);
                    intent.putExtra("vid", videoShowBean.getId());
                    startActivity(intent);
                }
            });
            mLlRecommendVideoContainer.addView(recommendVideo);
        }
    }

    @Override
    public void getMoreReplySuccess(InterestVideoDetailBean bean) {
        if (mAdapter != null) {
            if (bean.getCode() == 200) {
                mSrlMyRefreshLayout.finishLoadmore();
                List<InterestVideoDetailBean.DataBean.VideoCommentBean> videoComment = bean.getData().getVideoComment();
                int size = videoComment.size();
                if (size == 0) {
                    isLoadFinished = true;
                    mSrlMyRefreshLayout.setLoadmoreFinished(true);
                    mSrlMyRefreshLayout.finishLoadmore();
                } else if (size == PAGE_SIZE * 2) {
                    isLoadFinished = false;
                    mSrlMyRefreshLayout.finishLoadmore(true);
                    mAdapter.appendData(videoComment);
                } else {
                    isLoadFinished = true;
                    mSrlMyRefreshLayout.setLoadmoreFinished(true);
                    mSrlMyRefreshLayout.finishLoadmore();
                    mAdapter.appendData(videoComment);
                }
            }
        }
    }

    @Override
    public void getMoreReplyError(Throwable throwable) {
        pageNum--;
        mSrlMyRefreshLayout.finishLoadmore(false);
    }

    @Override
    public void getAddReplySuccess(CodeBean bean) {
        if (bean.getCode() == 200) {
            // 评论成功之后设置输入框内容为空 如果是回复他人恢复默认hint内容
            mEtVideoReply.setText("");
            if (isReplyComment) {
                mEtVideoReply.setHint("添加评论");
                isReplyComment = false;
            }
            mBtnSubmitReply.setEnabled(true);
            Toast.makeText(this, "评论成功", 0).show();
            mSrlMyRefreshLayout.autoRefresh();
        }
    }

    @Override
    public void getAddReplyError(Throwable throwable) {
        Toast.makeText(this, "评论失败", 0).show();
        mBtnSubmitReply.setEnabled(true);
    }

    @Override
    public void onFollowedSuccess(FollowResultBean bean) {
        int code = bean.getCode();
        switch (code) {
            case 203:
                mTvIsFollowed.setText("已关注");
                break;
            case 204:
                mTvIsFollowed.setText("关注");
                break;
        }
    }

    @Override
    public void onFollowedError(Throwable throwable) {
        LogUtils.e(throwable.getMessage(), "onFollowedError");
        Toast.makeText(this, "关注失败", 0).show();
    }

    /**
     * 删除评论成功
     *
     * @param bean 结果码 200 = 成功
     */
    @Override
    public void onDelReplySuccess(CodeBean bean, int position) {
        int code = bean.getCode();
        switch (code) {
            case 200:
                mAdapter.removeData(position);
                if (mAdapter.getList().isEmpty()) {
                    mCommentEmptyWarning.setVisibility(View.VISIBLE);
                }
                break;
            case 400:
                Toast.makeText(this, "删除失败", 0).show();
                break;
            case 406:
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 删除评论请求失败
     *
     * @param throwable 异常
     */
    @Override
    public void onDelReplyError(Throwable throwable) {
        LogUtils.e(throwable.getMessage(), "onDelReplyError");
        Toast.makeText(this, "请求失败", 0).show();
    }

    /**
     * 当Activity执行onResume()时让WebView执行resume
     */
    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (isOnPause) {
                if (mWvVideoContainer != null) {
                    mWvVideoContainer.getClass().getMethod("onResume").invoke(mWvVideoContainer, (Object[]) null);
                }
                isOnPause = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (mWvVideoContainer != null) {
                mWvVideoContainer.getClass().getMethod("onPause").invoke(mWvVideoContainer, (Object[]) null);
                isOnPause = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        if (mWvVideoContainer != null) {
            mWvVideoContainer.getSettings().setBuiltInZoomControls(true);
            mWvVideoContainer.setVisibility(View.GONE);
            mWvVideoContainer.destroy();
            mWvVideoContainer = null;
        }
        isOnPause = false;
        CustomProgressDialog.stopLoading();
        super.onDestroy();
    }
}